import React, { useState, useEffect, useMemo } from 'react';
import { Timeline, Card, Tag, Typography, Spin, Empty, message } from 'antd';
import { ExperimentOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { projectApi, experimentApi } from '../../services/api';
import { ExperimentRun } from '../../types';
import ContributionCalendar from './ContributionCalendar';
import '../../pages/Home.css';

const { Title, Text, Paragraph } = Typography;

interface ExperimentWithProject extends ExperimentRun {
  projectName?: string;
  projectNameEn?: string;
}

interface DayGroup {
  date: string; // YYYY-MM-DD
  dateLabel: string; // 格式化的日期显示
  experiments: ExperimentWithProject[];
}

interface ExperimentTimelineProps {
  onExperimentClick?: (experiment: ExperimentWithProject) => void;
}

const ExperimentTimeline: React.FC<ExperimentTimelineProps> = ({ onExperimentClick }) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [experiments, setExperiments] = useState<ExperimentWithProject[]>([]);
  const [dayGroups, setDayGroups] = useState<DayGroup[]>([]);

  // 加载所有实验数据
  const loadAllExperiments = async () => {
    try {
      setLoading(true);
      
      // 1. 获取所有项目
      const projects = await projectApi.getProjects();
      
      // 2. 获取每个项目的实验列表
      const experimentPromises = projects.map(async (project) => {
        try {
          const experiments = await experimentApi.getExperiments(project.name_en, 0, 1000);
          // 为每个实验添加项目信息
          return experiments.map(exp => ({
            ...exp,
            projectName: project.name,
            projectNameEn: project.name_en,
          }));
        } catch (error) {
          console.error(`Failed to load experiments for project ${project.name_en}:`, error);
          return [];
        }
      });
      
      const experimentArrays = await Promise.all(experimentPromises);
      const allExperiments = experimentArrays.flat();
      
      // 按创建时间降序排序
      allExperiments.sort((a, b) => {
        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
      });
      
      setExperiments(allExperiments);
    } catch (error) {
      console.error('Failed to load experiments:', error);
      message.error('加载实验记录失败');
    } finally {
      setLoading(false);
    }
  };

  // 按日期分组实验（使用 useMemo 优化性能）
  const dayGroupsMemo = useMemo(() => {
    if (experiments.length === 0) return [];
    
    const groups: { [key: string]: ExperimentWithProject[] } = {};
    
    experiments.forEach(exp => {
      const date = new Date(exp.created_at);
      const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      
      if (!groups[dateKey]) {
        groups[dateKey] = [];
      }
      groups[dateKey].push(exp);
    });
    
    // 转换为数组并按日期降序排序
    return Object.keys(groups)
      .sort((a, b) => b.localeCompare(a)) // 降序
      .map(dateKey => {
        const date = new Date(dateKey);
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        
        let dateLabel = '';
        const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
        const yesterdayKey = `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, '0')}-${String(yesterday.getDate()).padStart(2, '0')}`;
        
        if (dateKey === todayKey) {
          dateLabel = '今天';
        } else if (dateKey === yesterdayKey) {
          dateLabel = '昨天';
        } else {
          dateLabel = `${date.getMonth() + 1}月${date.getDate()}日`;
          // 如果不是今年，显示年份
          if (date.getFullYear() !== today.getFullYear()) {
            dateLabel = `${date.getFullYear()}年${dateLabel}`;
          }
        }
        
        return {
          date: dateKey,
          dateLabel,
          experiments: groups[dateKey],
        };
      });
  }, [experiments]);

  useEffect(() => {
    loadAllExperiments();
  }, []);

  // 当实验数据变化时，更新分组
  useEffect(() => {
    setDayGroups(dayGroupsMemo);
  }, [dayGroupsMemo]);

  // 格式化时间
  const formatTime = (dateString: string): string => {
    const date = new Date(dateString);
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
  };

  // 格式化日期和时间
  const formatDateTime = (dateString: string): string => {
    const date = new Date(dateString);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
  };

  // 跳转到实验详情
  const handleExperimentClick = (experiment: ExperimentWithProject) => {
    if (onExperimentClick) {
      onExperimentClick(experiment);
    } else if (experiment.projectNameEn) {
      navigate(`/project/${experiment.projectNameEn}/experiments`);
    }
  };

  if (loading) {
    return (
      <div style={{ padding: '40px', textAlign: 'center' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>
          <Text type="secondary">加载实验记录中...</Text>
        </div>
      </div>
    );
  }

  return (
    <div className="home-container" style={{ padding: '24px' }}>
      <div className="home-header">
        <Title level={2} style={{ margin: 0 }}>
          实验动态
        </Title>
        <Text type="secondary">
          共 {experiments.length} 条实验记录
        </Text>
      </div>

      {/* 贡献日历 */}
      {experiments.length > 0 && (
        <ContributionCalendar experiments={experiments} />
      )}

      {dayGroups.length === 0 ? (
        <Empty
          description="暂无实验记录"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <Text type="secondary">开始进行实验后，记录会显示在这里</Text>
        </Empty>
      ) : (
        <div className="timeline-container">
          <Timeline 
            mode="left"
            items={dayGroups.map((group) => ({
              key: group.date,
              color: 'blue',
              children: (
                <>
                  <div className="timeline-date-header">
                    <Title level={4} style={{ margin: 0, fontSize: '18px' }}>
                      {group.dateLabel}
                    </Title>
                    <Tag color="blue">{group.experiments.length} 条实验</Tag>
                  </div>

                  <div className="experiments-list">
                    {group.experiments.map((experiment) => (
                      <Card
                        key={`${experiment.project_id}-${experiment.id}`}
                        className="experiment-card"
                        hoverable
                        onClick={() => handleExperimentClick(experiment)}
                        style={{ marginBottom: '12px' }}
                      >
                        <div className="experiment-card-header">
                          <div className="experiment-card-title">
                            <ExperimentOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
                            <Text strong>
                              {experiment.name || `实验 #${experiment.id}`}
                            </Text>
                            <Tag color="processing" style={{ marginLeft: '8px' }}>
                              {experiment.projectName || `项目 ${experiment.project_id}`}
                            </Tag>
                          </div>
                          <Text type="secondary" className="experiment-time">
                            {formatTime(experiment.created_at)}
                          </Text>
                        </div>
                        
                        {experiment.description && (
                          <Paragraph
                            ellipsis={{ rows: 2, expandable: false }}
                            style={{ marginTop: '12px', marginBottom: 0, color: '#666' }}
                          >
                            {experiment.description}
                          </Paragraph>
                        )}
                        
                        <div className="experiment-card-footer">
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            {formatDateTime(experiment.created_at)}
                          </Text>
                        </div>
                      </Card>
                    ))}
                  </div>
                </>
              ),
            }))}
          />
        </div>
      )}
    </div>
  );
};

export default ExperimentTimeline;

